#include <QtGui>
#include <QtWebKit/QWebFrame>
#include <iostream>

#include "MainWindow.h"
#include "WebBrowser.h"
#include "Bookmarks.h"
#include "Translate.h"
#include "TextWindow.h"
#include "Log.h"

// =========== SLOTS ==============
void MainWindow::slot_addressEntered()
{
	WebBrowser *browser = currentBrowser();
  if (!browser) browser = addBrowser(true, QUrl::fromUserInput(m_edAddress->text()).toString());
  else {
		browser->m_tid = 0;
		loadUrl(browser, QUrl::fromUserInput(m_edAddress->text()));
		browser->m_original = true;
		addTrustedHost(QUrl::fromUserInput(m_edAddress->text()).host());
	}
}

void MainWindow::slot_linkClicked(const QUrl& url)
{
	WebBrowser *s = static_cast<WebBrowser*> (sender());
	Log::m_log << "Link clicked: " << url.toString() << "\n";
	s->m_tid = 0;
	loadUrl(s, url);
}

void MainWindow::slot_newTab()
{
	WebBrowser *browser = addBrowser(true);
	m_tab->setCurrentWidget(browser);
}

void MainWindow::browserAction(QWebPage::WebAction action)
{
	WebBrowser *browser = currentBrowser();
	if (browser) {
    browser->pageAction(action)->trigger();
  }
}

void MainWindow::slot_backward()
{
  browserAction(QWebPage::Back);
}

void MainWindow::slot_forward()
{
  browserAction(QWebPage::Forward);
}

void MainWindow::slot_copyText()
{
  WebBrowser *browser = currentBrowser();
  if (browser) {
    QString text = browser->selectedText();
    if (!text.isEmpty())
      browserAction(QWebPage::Copy);
    else {
      Log::m_log << "No text in browser, use title text" << endl;
      text = browser->title();
      QApplication::clipboard()->setText(text);
    }
  }
  m_actCopyText->setToolTip(QApplication::clipboard()->text());
}

void MainWindow::slot_searchText()
{
	WebBrowser *browser = currentBrowser();
	if (browser) {
    QString text = browser->selectedText().trimmed();
    if (text.isEmpty()) {
      Log::m_log << "No text in browser, use clipboard text" << endl;
      text = QApplication::clipboard()->text();
    }
    QString url = "http://www.google.com/search?ie=UTF-8&q="+text;
    WebBrowser *searchBrowser = addBrowser(true, url);
    m_tab->setCurrentWidget(searchBrowser);
  }
}

void MainWindow::slot_updateAddress()
{
	WebBrowser *browser = currentBrowser();
	if (browser)
		m_edAddress->setText(browser->url().toString());
}

void MainWindow::slot_urlChanged(const QUrl& url)
{
	Log::m_log << "Url Changed " << url.toString() << "\n";
	WebBrowser *s = static_cast<WebBrowser*> (sender());
	WebBrowser *browser = currentBrowser();
	if (s == browser && focusWidget() != m_edAddress)
		m_edAddress->setText(url.toString());
	QString hostname = s->url().host();
	if (s->m_original) {
		addTrustedHost(hostname);
	}
	else {
		if (!m_trustedHost.contains(hostname)) {  // ad-block
			s->deleteLater();
			m_tab->removeTab(m_tab->indexOf(s));
		}
	}
}

void MainWindow::slot_titleChanged(const QString& title)
{
	Log::m_log << "Title Changed: "/* << title*/ << endl;
	WebBrowser *s = static_cast<WebBrowser*> (sender());
	if (s) {
		int index = m_tab->indexOf(s);
		if (index >= 0) m_tab->setTabText(index, QString("translator ")+QString::number(index) /*title.left(10)*/);
	}
}

void MainWindow::slot_saveBookmark()
{
  this->m_bookmark->save("bookmarks");
}

void MainWindow::slot_loadBookmark()
{
  this->m_bookmark->load("bookmarks");
  slot_refreshBookmarkToolbar();
}

void MainWindow::slot_removeBookmark()
{
  WebBrowser *browser = currentBrowser();
  if (browser) {
    QString url = browser->url().toString();
    this->m_bookmark->remove(url);
    slot_refreshBookmarkToolbar();
    slot_saveBookmark();
  }
}

void MainWindow::slot_refreshBookmarkToolbar()
{
	m_tbBookmark->clear();
	Q_FOREACH(QAction* a, m_actBookmarkVec) {
		a->deleteLater();
	}
	m_actBookmarkVec.clear();
	Q_FOREACH(const Bookmark& b, *m_bookmark) {
		QAction* a = new QAction(b.m_title.left(20), this);
		a->setToolTip(b.m_url);
		m_actBookmarkVec << a;
		m_tbBookmark->addAction(a);
		connect(a, SIGNAL(triggered()), this, SLOT(slot_bookmarkClicked()));
	}
}

void MainWindow::slot_bookmarkClicked()
{
	QAction *a = static_cast<QAction*>(sender());
	for (int i = 0; i < m_actBookmarkVec.size(); i++) if (m_actBookmarkVec[i] == a) {
		Log::m_log << "Bookmark clicked: " << m_bookmark->at(i).m_url << "\n";
    QString url = m_bookmark->at(i).m_url;
		WebBrowser *browser = currentBrowser();
	  if (!browser) browser = addBrowser(true, url);
    else {
			loadUrl(browser, QUrl::fromUserInput(url));
			browser->m_original = true;
			addTrustedHost(QUrl::fromUserInput(url).host());
			browser->setFocus();
		}
		break;
	}
}

void MainWindow::slot_bookmark()
{
	WebBrowser *browser = currentBrowser();
	if (browser) {
		QString title = browser->title();
		QUrl url = browser->url();
		*m_bookmark << Bookmark(title, url);
		slot_refreshBookmarkToolbar();
		slot_saveBookmark();
	}
}

void MainWindow::slot_translate()
{
	WebBrowser *browser = currentBrowser();
	if (!browser) return;
	Log::m_log << "Translating " << browser->title() << "\n"
		<< "  at " << browser->url().toString() << "\n";
	const QWebFrame* frame = browser->page()->mainFrame();
	Translator *t = new Translator(browser, frame->toHtml(), browser->url()/*frame->baseUrl()*/, this); // after this, browser->m_tid = t->m_id
	connect(t, SIGNAL(finished()), this, SLOT(slot_translateFinished()));
	t->start();
}

void MainWindow::slot_translateText()
{
	WebBrowser *browser = currentBrowser();
	if (!browser ) return;
	const QWebFrame* frame = browser->page()->mainFrame();
	if (!frame) return;
	Log::m_log << "Translating " << browser->title() << "\n"
		<< "  at " << browser->url().toString() << "\n";

  QString text = frame->toPlainText();
  text.replace("&nbsp;", " ");
  text.replace("<br/>", "\n\n");
  m_textWindow->setOriginalText(text);
  m_textWindow->show();
  //m_textWindow->showMaximized();
  m_textWindow->setFocus();
  m_textWindow->hvFocus();
  this->showMinimized();
  Log::m_log << "Open text window" << endl;    
}

void MainWindow::slot_translateFinished() 
{
	Translator* t = static_cast<Translator*>(sender());
	Log::m_log << "Translation done: id = " << t->m_id << " browser->m_tid = " << t->m_browser->m_tid
		<< " url = " << t->m_url.toString() << "\n";
	if (t->m_id == t->m_browser->m_tid) {                    // check for correct id
		t->m_browser->setHtml(t->m_trHtml, t->m_url);
		t->m_browser->m_tid = 0;
	}
	//WebBrowser *tr_browser = m_browserMap[t->m_browser];
	//tr_browser->setHtml(t->m_trHtml, t->m_url);
	//tr_browser->show();
	t->deleteLater();
}

void MainWindow::slot_loadFinished(bool) {
	WebBrowser *s = static_cast<WebBrowser*> (sender());
  disconnect(s, SIGNAL(loadFinished(bool)), this, SLOT(slot_loadFinished(bool)));
	const QWebFrame* frame = s->page()->mainFrame();
	Translator *t = new Translator(s, frame->toHtml(), frame->baseUrl(), this); // after this, browser->m_tid = t->m_id
	connect(t, SIGNAL(finished()), this, SLOT(slot_translateFinished()));
	t->start();
}

void MainWindow::slot_loadProgress(int progress) {
  WebBrowser *s = static_cast<WebBrowser*> (sender());
//  Log::m_log << "Load progress: " << s->url().toString() << "\n";
  int index = m_tab->indexOf(s);
  if (progress < 100)
    m_tab->setTabText(index, QString::number(progress) + " Translator " + QString::number(index));
  else
    m_tab->setTabText(index, "-- Translator " + QString::number(index) + " --");
}

void MainWindow::slot_autoTranslateFinished() 
{
}

void MainWindow::slot_tabCloseRequested(int index)
{
  WebBrowser *s = static_cast<WebBrowser*> (m_tab->widget(index));
  m_tab->removeTab(index);
  s->deleteLater();
}

void MainWindow::slot_saveTrustedHost()
{
	QFile file("trusted");
	file.open(QIODevice::WriteOnly);
	QDataStream out(&file);   // we will serialize the data into the file
	out << this->m_trustedHost; // serialize a set of hosts
}

void MainWindow::slot_loadTrustedHost()
{
	QFile file("trusted");
	file.open(QIODevice::ReadOnly);
	if (file.isOpen()) {
		QDataStream in(&file);   // we will serialize the data into the file
		in >> m_trustedHost; // serialize a set of hosts
		Log::m_log << "Read " << m_trustedHost.size() << " hosts." << endl;
	}
}

void MainWindow::slot_linkHovered(const QString & link, const QString & title, const QString & textContent)
{
  QWebPage *s = static_cast<QWebPage*> (sender());
  QUrl url = QUrl::fromUserInput(link);
  QString tr = Translator::translateText(textContent);
  Log::m_log << "++link hover (" << url.host() << ") : " << tr.toUtf8() << endl;
  if (s->view() == currentBrowser()) {
    if (textContent.isEmpty())
      m_lblStatus->clear();
    else {
      QString msg = tr + " (" + url.toString() + ")";
      msg = msg.left(150);
      m_lblStatus->setText(msg);
    }
    m_currentUrl = url;
  }
}
